/**
 * 生成随机字符串
 * @param {number} length 
 * @returns 
 */
function _randomStr(length) {
  return Math.pow(Math.random(), 2).toString(32).substr(-length)
}

/**
 * 生成随机字符串
 * @param {number} length 后面随机字符串的长度
 * @param {string} prefix 字符串前缀
 * @param {string} connection 前缀和后面随机字符串的连接字符
 * @returns 
 */
export function randomStr(length, prefix = 'ultrame', connection = '') {
  return `${prefix}${connection}${_randomStr(length)}`
}

/**
 * 生成随机数字（生成minNum ~ range+minNum之间的数）
 * @param {number} range
 * @param {number} minNum 
 * @returns 
 */
export function randomNum(range, minNum) {
  return Math.floor(Math.random() * range) + minNum;
}

/**
 * 通过组件id，查找组件类的实例
 * @param {array} widgets 
 * @param {string} id 
 * @returns 组件类的实例
 */
export function findSelectedWidgetById(widgets, id) {
  let result = null

  function find(widgets, id, replace) {
    for (let i = 0, len = widgets.length; i < len; i++) {
      if (Array.isArray(widgets[i] && widgets[i].widgets)) {
        find(widgets[i].widgets, id, true)
      }
      if (widgets[i] && widgets[i].id === id) {
        result = replace ? widgets.splice(i, 1, null) : widgets.splice(i, 1)
        break
      }
    }
  }
  find(widgets, id, false)
  return result && result[0]
}

/**
 * 通过id查找并返回对应的组件类实例
 * @param {Array} data 
 * @param {String} id 
 * @returns 
 */
export const deepFindWidgetById = (data, id) => {
  let result = null
  const findData = (data, id) => {
    if (result) return
    for (let i = 0, len = data.length; i < len; i++) {
      if (Array.isArray(data[i]?.widgets)) {
        findData(data[i].widgets, id)
      }
      if (data[i]?.id === id) {
        result = data[i]
      }
    }
  }
  findData(data, id)
  return result
}

/**
 * 判断 str 是否符合正则表达式
 * @param {String} str 
 * @returns 
 */
export const regExpCheck = (str) => {
  let result = false
  try {
    result = eval(str) instanceof RegExp
  } catch (e) {
    result = false
  }
  return result
}